package com.ax.center.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.ax.center.ExceptionHandler.BusinessException;
import com.ax.center.dto.*;
import com.ax.center.entity.Staff;
import com.ax.center.entity.Users;
import com.ax.center.mapper.LoginDTOMapper;
import com.ax.center.mapper.UserDTOMapper;
import com.ax.center.mapper.UserInfoMapper;
import com.ax.center.mapper.UsersMapper;
import com.ax.center.service.StaffService;
import com.ax.center.service.UserRoleService;
import com.ax.center.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zy
 * @date 2023/7/4 11:10
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserInfoMapper userInfoMapperl;
    
    @Autowired
    private StaffService staffService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserDTOMapper userDTOMapper;

    @Autowired
    private LoginDTOMapper loginDTOMapper;

    // 加密密码
    public String encryptPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedHash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            return bytesToHexString(encodedHash);
        } catch (NoSuchAlgorithmException e) {
            // 处理算法不支持的异常
            e.printStackTrace();
            return null;
        }
    }

    // 将字节数组转换为十六进制字符串
    private String bytesToHexString(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                result.append('0');
            }
            result.append(hex);
        }
        return result.toString();
    }

    // 使用加密后的密码进行验证
    @Override
    public Users checkPW(Long id, String password) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", id);
        Users users = usersMapper.selectOne(queryWrapper);

        if (users != null) {
            String storedPassword = users.getPassword();
            String hashedPassword = encryptPassword(password);

            if (storedPassword.equals(hashedPassword)) {
                return users;
            }
        }
        return null; // 密码不匹配或用户不存在
    }

    // 修改密码
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse updatePW(Long id, String newPW) {
        if (newPW.length() < 10) {
            return ApiResponse.fail("密码长度必须大于9");
        }

        // 加密新密码
        String encryptedPassword = encryptPassword(newPW);

        UpdateWrapper<Users> updateWrapper = new UpdateWrapper<Users>().eq("staff_id", id).set("password", encryptedPassword);
        int updateCount = usersMapper.update(null, updateWrapper);

        if (updateCount == 0) {
            return ApiResponse.fail("修改密码失败");
        }

        return ApiResponse.ok("修改密码成功");
    }

    @Override
    public ApiResponse queryUserByDeName(String departmentName) {
        List<Users> deps = query().eq("department_Name", departmentName).list();
        return ApiResponse.ok(deps);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse queryUserByName(String name) {
        Users one = query().eq("name", name).one();
        if(one!=null){
            return ApiResponse.ok(one);
        }else {
            return ApiResponse.fail("不存在该用户");
        }
    }


    @Override
        public ApiResponse queryAllDeName() {
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("department_name").groupBy("department_name");
            List<Users> employees = usersMapper.selectList(queryWrapper);
            List<String> departments = new ArrayList<>();
            for (Users employee : employees) {
                departments.add(employee.getDepartmentName());
            }
            return ApiResponse.ok(departments);
    }

    @Override
    public ApiResponse queryByStaffId(Long staffId) {
        Users users = query().eq("staff_id", staffId).one();
        return ApiResponse.ok(users);
    }

    @Override
    public ApiResponse queryAll() {
        List<UserInfoDto> users = userInfoMapperl.getAllUsersWithStaffInfo();
        return ApiResponse.ok(users);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse insertUser(NewUserDTO newUserDTO) {
        try {
            String status = newUserDTO.getStatus();
            Long roleId = newUserDTO.getRoleId();
            String sex = newUserDTO.getSex();
            String name = newUserDTO.getName();
            String deName = newUserDTO.getDeName();
            Staff staff = staffService.insert(status);
            Long staffId = staff.getId();
            Users users = new Users();
            users.setSex(sex)
                    .setName(name)
                    .setDepartmentName(deName)
                            .setStaffId(staffId)
                                    .setPassword(" ");
               usersMapper.insert(users);
            System.out.println(users);
            Long userId = users.getId();
            userRoleService.insertRole(userId,roleId);
            return ApiResponse.ok(staffId);
        } catch (Exception e) {
            throw new BusinessException("新增用户失败", e);
        }
    }

    @Override
    public ApiResponse deleteUser(Long satffId) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("staff_id",satffId);
        remove(usersQueryWrapper);
        return ApiResponse.ok("删除成功");
    }

    @Override
    public ApiResponse getAllStaffsWithRoleAndAuth() {
        List<UserDTO> userDTO = userDTOMapper.getAllStaffsWithRoleAndAuth();
        return ApiResponse.ok(userDTO);
    }

    @Override
    public ApiResponse getAllRolesWithStaffInfo() {
        List<UserDTO> allRolesWithStaffInfo = userDTOMapper.getAllRolesWithStaffInfo();
        return ApiResponse.ok(allRolesWithStaffInfo);
    }

    @Override
    public ApiResponse getStaffInfoByRoleName(String roleName) {
        List<UserDTO> staffInfoByRoleName = userDTOMapper.getStaffInfoByRoleName(roleName);
        return ApiResponse.ok(staffInfoByRoleName);
    }

    @Override
    public ApiResponse getStaffInfoByDeName(String deName) {
        List<UserDTO> staffInfoByDeName = userDTOMapper.getStaffInfoByDeName(deName);
        return ApiResponse.ok(staffInfoByDeName);
    }

    @Override
    public ApiResponse getStaffInfoByUserName(String userName) {
        List<UserDTO> staffInfoByUserName = userDTOMapper.getStaffInfoByUserName(userName);
        return ApiResponse.ok(staffInfoByUserName);
    }

    @Override
    public ApiResponse updateDeName(Long staffId, String deName) {
        boolean update = update().set("department_name", deName).eq("staff_id", staffId).update();
        if(BooleanUtil.isTrue(update)){
            return ApiResponse.ok("修改成功");
        }else {
            return ApiResponse.fail("修改失败");
        }
    }

    @Override
    public ApiResponse getStaffInfoByStaffId(Long staffId) {
        List<UserDTO> staffInfoByStaffId = userDTOMapper.getStaffInfoByStaffId(staffId);
        return ApiResponse.ok(staffInfoByStaffId);
    }

    @Override
    public ApiResponse getUserDetailsByStaffId(Long staffId) {
        LoginDTO userDetailsByStaffId = loginDTOMapper.getUserDetailsByStaffId(staffId);
        return ApiResponse.ok(userDetailsByStaffId);
    }


}
